package com.spica.spicaschool.service

import android.annotation.SuppressLint
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.Service
import android.content.Intent
import android.graphics.BitmapFactory
import android.os.Build
import android.os.IBinder
import androidx.core.app.NotificationCompat
import com.spica.spicaschool.R
import com.spica.spicaschool.ui.sportMap.SportMapActivity
import com.spica.spicaschool.utils.SpUtils
import timber.log.Timber
import java.util.*
import kotlin.concurrent.timerTask

/**
 * 运动计时服务
 */
const val SPORT_TIME_ACTION = "sport_time"
const val SIGN_TIMES = "timeS"
private const val SP_TIME = "times_sp"

class SportTimeService : Service() {

    // 正在计时？
    private var isTiming = false
        set(value) {
            when (value) {
                true -> {
                    timer = Timer()
                    timer?.schedule(timerTask, 1000, 1000)
                }
                false -> {
                    timer?.cancel()
                }
            }
            field = value
        }

    // 时长
    private var times: Long = 0

    override fun onBind(intent: Intent?): IBinder? = null

    private var timer: Timer? = Timer()

    private val timerTask = timerTask {
        times++
        Timber.e("秒：$times")
        sendBroadcast()
    }

    @SuppressLint("UnspecifiedImmutableFlag")
    override fun onCreate() {
        super.onCreate()
        //获取时间记录缓存
        times = SpUtils.getSpValue(key = SP_TIME, defaultVal = 0, context = this)






        //创建顶部通知提示
        val notification = NotificationCompat.Builder(this)

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channelId = "sport"
            val channelName = "运动监控"
            val importance = NotificationManager.IMPORTANCE_HIGH
            val channel = NotificationChannel(channelId, channelName, importance)
            val manager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
            manager.createNotificationChannel(channel)
            notification.setChannelId(channelId)
        }

        val intent = Intent(this, SportMapActivity::class.java)
        val pendingIntent = PendingIntent.getActivity(this, 0, intent, 0)
        notification.setContentTitle("正在为你的运动计时..")
            .setContentText("查看您的运动轨迹")
            .setWhen(System.currentTimeMillis())
            .setSmallIcon(R.drawable.ic_circle)
            .setLargeIcon(BitmapFactory.decodeResource(resources, R.drawable.ic_app))
            .setContentIntent(pendingIntent)
        startForeground(1, notification.build())
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        setTime(true)
        return super.onStartCommand(intent, flags, startId)
    }


    override fun onDestroy() {
        setTime(false)
        super.onDestroy()
    }

    private fun sendBroadcast() {
        val intent = Intent(SPORT_TIME_ACTION)
        intent.putExtra(SIGN_TIMES, times)
        sendBroadcast(intent)
    }

    //设置计时状态
    private fun setTime(timing: Boolean) {
        this.isTiming = timing
    }

    //是否正在计时
    private fun isTime(): Boolean = isTiming
}
